/* 
 * StikiWeb Wiki - a Wiki for Hierarchical Organizations
 * $Id: StrutsFriendlyMagicSelfGrowingArrayList.java,v 1.3 2006/07/20 21:17:58 biglee Exp $
 * 
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the StikiWeb Wiki 
 *
 * The Initial Developer of the Original Code is Lee Haslup (biglee@haslups.com).
 * Portions created by the Initial Developer are Copyright (C) 2004
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * ***** END LICENSE BLOCK ***** 
 */
package org.stikiweb.struts;

import java.util.ArrayList;

import org.stikiweb.contentMagnager.StikiWebContext;

/**
 * @author Allen L (BigLee) Haslup
 *
 */
public class StrutsFriendlyMagicSelfGrowingArrayList extends ArrayList {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4157339264978642929L;

	// maxGrowth is the limit for the number of entries
	// to grow in a single step.  Since we are not guaranteed
	// that indexes will be presented in order it should be
	// set at the largest expected index.  It protects the
	// server from a request for, say, index=100000000.
	protected final static int maxGrowth = 100;
	
	Class fillerObject;
	
	StrutsFriendlyMagicSelfGrowingArrayList() {
	}
	public StrutsFriendlyMagicSelfGrowingArrayList(Class filler) {
		super();
		fillerObject=filler;
	}
	/* (non-Javadoc)
	 * @see java.util.List#get(int)
	 */
	public Object get(int index) {
		try {
			while(size()<=index && size()+maxGrowth > index) add(fillerObject.newInstance());
		} catch (Exception e) {
			StikiWebContext.mutter("Rats!!!\n");
			// let's just hope this doesn't happen.  If it does
			// we'll throw an index out of bounds exception below.
		}
		return super.get(index);
	}

	/* (non-Javadoc)
	 * @see java.util.List#set(int, java.lang.Object)
	 */
	public Object set(int index, Object element) {
		try {
			while(size()<=index && size()+maxGrowth > index) add(fillerObject.newInstance());
		} catch (Exception e) {
			// let's just hope this doesn't happen.  If it does
			// we'll throw an index out of bounds exception below.
		}
		return super.set(index, element);
	}

}
